﻿using LD.Host.Tool;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace LD.Tool
{
    public partial class VmRunFrm : FrmToolBase
    {
        public VmRunFrm()
        {
            InitializeComponent();

            this.Text = TB_Tool.Name;
            this.btn_ok.Click += Btn_ok_Click;
            this.Shown += ToolReadImageFrm_Shown;
        }

        private void ToolReadImageFrm_Shown(object sender, EventArgs e)
        {
            Init();
        }

        private void Btn_ok_Click(object sender, EventArgs e)
        {
            var param = new VmRunParam();
            param.FlowName = this.cob_camera.Text;
            //回写PLC参数
            if (param.EchoPLC == null)
                param.EchoPLC = new List<EchoPLC>();
            foreach (DataGridViewRow item in this.dgv_data.Rows)
            {
                if (item.Cells["PLC地址"] != null
                    && item.Cells["数据类型"] != null
                    && item.Cells["PLC地址"].Value != null
                    && item.Cells["数据类型"].Value != null
                    )
                {
                    param.EchoPLC.Add(new EchoPLC()
                    {
                        Address = item.Cells["PLC地址"].Value.ToString(),
                        DataType = item.Cells["数据类型"].Value.ToString(),
                        IsEcho = true
                    }); ;
                }
            }
            var paramString = Newtonsoft.Json.JsonConvert.SerializeObject(param);
            TB_Tool.Param = paramString;
        }

        private void Init()
        {
            if (TB_Tool.Param == null)
                return;
            var param = Newtonsoft.Json.JsonConvert.DeserializeObject<VmRunParam>(TB_Tool.Param);
            if (param != null)
            {
                this.cob_camera.Text = param.FlowName;

                //回写PLC信息展示
                foreach (var item in param.EchoPLC)
                {
                    var index = this.dgv_data.Rows.Add();
                    this.dgv_data["数据类型", index].Value = item.Address;
                    this.dgv_data["PLC地址", index].Value = item.DataType;
                }
            }
        }

        private void panel4_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
